package com.lobo.blog.controller;

import com.lobo.blog.entity.Comment;
import com.lobo.blog.entity.User;
import com.lobo.blog.service.BlogService;
import com.lobo.blog.service.CommentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * className: CommentController<br/>
 * author: MacieSerenity <br/>
 * date: 2022-10-14 17:15
 **/
@Controller
public class CommentController {

    @Resource
    private CommentService commentService;

    @Resource
    private BlogService blogService;

    @Value("${comment.avatar}")
    private String avatarPath;

    @RequestMapping("/comments/{blogId}")
    public String comments(@PathVariable Integer blogId,
                           Model model) {
        model.addAttribute("comments", commentService.listCommentByBlogId(blogId));
        return "blog :: commentList";
    }

    @RequestMapping("/comments")
    public String commentPost(Comment comment, HttpSession httpSession) {
        Integer blogId = comment.getBlog().getId();
        comment.setBlog(blogService.getBlogById(blogId));
        comment.setBlogId(blogId);
        User user = (User) httpSession.getAttribute("user");
        if (user!=null){
            comment.setAvatar(user.getAvatar());
            comment.setIsAdmin(true);
//            comment.setNickname("高贵的管理员");
        }else {
            comment.setIsAdmin(false);
            comment.setAvatar(avatarPath);
        }
        commentService.saveComment(comment);
        return "redirect:/comments/" + comment.getBlog().getId();
    }

}
